package org.dromara.system.kernel;

import com.alibaba.fastjson2.JSONObject;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.utils.DateUtils;
import org.dromara.system.domain.PayApp;
import org.dromara.system.domain.PayGroup;
import org.dromara.system.domain.PayGroupLog;
import org.dromara.system.mapper.PayGroupLogMapper;
import org.dromara.system.mapper.PayGroupMapper;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;

import java.util.concurrent.CompletableFuture;

@RefreshScope
@Service
@RequiredArgsConstructor
public class GroupLogInsertKernel {

    private final PayGroupLogMapper payGroupLogMapper;
    private final PayGroupMapper payGroupMapper;

    public void insert(PayApp app, String name, String params, R<?> r, Long time) {
        CompletableFuture.runAsync(() -> {
            if (R.isSuccess(r)) {
                return;
            }
            PayGroupLog payGroupLog = new PayGroupLog();
            payGroupLog.setAppId(app.getAppId());
            payGroupLog.setOperate(name);
            payGroupLog.setParamsLog(params);
            payGroupLog.setReturnLog(JSONObject.toJSONString(r));
            payGroupLog.setTime(time);
            payGroupLog.setStatus(2);
            payGroupLog.setGroupId(app.getGroupId());
            if (app.getGroupId() != null) {
                PayGroup group = payGroupMapper.selectById(app.getGroupId());
                if (group != null) {
                    payGroupLog.setGroupName(group.getGroupName());
                }
            }
            payGroupLog.setClientId(app.getClientId());
            payGroupLog.setClientName(app.getClientName());
            payGroupLog.setAgentId(app.getAgentId());
            payGroupLog.setAgentName(app.getAgentName());
            payGroupLog.setManagerId(app.getManagerId());
            payGroupLog.setManagerName(app.getManagerName());
            payGroupLog.setCreateTime(DateUtils.getNowDate());

            payGroupLogMapper.insert(payGroupLog);
        });
    }
}
